package atguigu.cglib.cglibNoInterface;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**
 * 手动实现一个代理类
 * 
 * 代理模式的好处,可以在要被代理的对象的方法外,增加一些代码逻辑
 * 
 * @author ex_yejing1
 *
 */
public class ProductProxy implements MethodInterceptor {

	private Object target;
	private static ProductProxy instance = new ProductProxy();
	private ProductProxy() {}
	public static ProductProxy getInstance() {
		return instance;
	}

	public Object getProxy(Object target) {
		this.target = target;
		return Enhancer.create(target.getClass(), this);
	}
	
	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		Object returnValue = null;
		if ("saleProduct".equals(method.getName())) {
			pre(); // 前置处理
			Float money = (float) (0.8 * (Float) args[0]);
			returnValue = method.invoke(target, money);
			after(); // 后置处理
		}
		return returnValue;
	}
	
	private void pre() {
		System.out.println("前置处理");
	}

	private void after() {
		System.out.println("后置处理");
	}

}
